package henu.cn.androidhomework.Login;

import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import henu.cn.androidhomework.R;

public class AdvertisementActivity extends AppCompatActivity {
    boolean flag;//标识正式页面是否已经启动
    private MyCountDownTimer time;
    private Button btnStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        flag = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advertisement);


        time = new MyCountDownTimer(10000, 1000);//广告的总的显示时间是10秒，间隔1秒
         time.start();
        btnStart = (Button) findViewById(R.id.btnStart);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                Intent intent = new Intent(AdvertisementActivity.this, LoginActivity.class);
                startActivity(intent);
                flag = true;
            }
        });
        //延后处理事件

       new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(AdvertisementActivity.this, LoginActivity.class);
                if (!flag)
                    startActivity(intent);
                finish();
            }
        }, 10000);

        //此处的时间与上面定时器倒计时的时间一致
    }
    //倒计时
    class MyCountDownTimer extends CountDownTimer {
        /**
         参数1-mMillisInFuture，设置倒计时的总时间（毫秒）
         参数2-mCountdownInterval，设置每次减去多少毫秒
         */
        private long mCountdownInterval;

        public MyCountDownTimer(long mMillisInFuture, long mCountdownInterval) {
            super(mMillisInFuture, mCountdownInterval);
            this.mCountdownInterval = mCountdownInterval;
        }

        /**
         * @param millisUntilFinished 还剩下的时间
         */
        @Override
        //onTick()方法是定期间隔回调的方法
        public void onTick(long millisUntilFinished) {
            btnStart.setClickable(true);


            btnStart.setText("点击跳过" + millisUntilFinished / mCountdownInterval + "秒");

        }

        @Override
//        onFinish()就是结束时回调的方法了
        public void onFinish() {
           /* btnStart.setText("欢迎！");
            btnStart.setClickable(true);*/
            Intent intent = new Intent(AdvertisementActivity.this, LoginActivity.class);
            if (!flag)
                startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(time!=null)
            time.cancel();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(time!=null)
            time.cancel();
    }
}
